package main

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"log"
	"yuekao3/api"
	"yuekao3/api/handler"
	"yuekao3/config"
	"yuekao3/dao"
	"yuekao3/dao/queue"
	"yuekao3/global"
	"yuekao3/inits"
	"yuekao3/model"
)

func main() {
	config.AppConfig()
	inits.Mysql()
	inits.GongChang("rabbitmq")
	r := gin.Default()
	api.Router(r)
	go workSub()
	go PublishPub()
	r.Run(":10002") // 监听并在 0.0.0.0:8080 上启动服务
}

func PublishPub() {

	msgs := queue.PublishSub("notification")

	forever := make(chan bool)
	//启用协程处理消息
	go func() {
		for d := range msgs {
			//消息逻辑处理，可以自行设计逻辑
			log.Printf("Received a message: %s", d.Body)
			var don handler.WSGroupReq
			json.Unmarshal(d.Body, &don)
			log.Println(don)
			for _, onlineConn := range global.OnlineUser {
				log.Println(don.Data.Message)
				handler.WSRespSuccess(onlineConn, don.Data.Message)

			}
		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}

func workSub() {
	msgs := queue.QueueSub("ltjlu")

	forever := make(chan bool)
	//启用协程处理消息
	go func() {
		for d := range msgs {
			//消息逻辑处理，可以自行设计逻辑
			log.Printf("Received a message: %s", d.Body)
			var chat model.ChatHistory
			json.Unmarshal(d.Body, &chat)
			dao.Create(&chat)
			for _, onlineConn := range global.OnlineUser {

				handler.WSRespSuccess(onlineConn, chat.Content)

			}
		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}
